<?php

class Nuo_Utility_Locale
{
    static public function getLanguageNameList()
    {
        // Languages
        $translate = Zend_Registry::get('Zend_Translate');
        $languageList = $translate -> getList();

        //$currentLocale = Zend_Registry::get('Locale')->__toString();

        // Prepare default langauge
        $defaultLanguage = NUO_DEFAULT_LANGUAGE;
		
        if (!in_array($defaultLanguage, $languageList))
        {
            if ($defaultLanguage == 'auto' && isset($languageList['en']))
            {
                $defaultLanguage = 'en';
            }
            else
            {
                $defaultLanguage = null;
            }
        }

        // Prepare language name list
        $languageNameList = array();
        $languageDataList = Zend_Locale_Data::getList(null, 'language');
        $territoryDataList = Zend_Locale_Data::getList(null, 'territory');

        foreach ($languageList as $localeCode)
        {
            $languageNameList[$localeCode] = Zend_Locale::getTranslation($localeCode, 'language', $localeCode);
            
            if (empty($languageNameList[$localeCode]))
            {
                if (false !== strpos($localeCode, '_'))
                {
                    list($locale, $territory) = explode('_', $localeCode);
                }
                else
                {
                    $locale = $localeCode;
                    $territory = null;
                }
                if (isset($territoryDataList[$territory]) && isset($languageDataList[$locale]))
                {
                    $languageNameList[$localeCode] = $territoryDataList[$territory] . ' ' . $languageDataList[$locale];
                }
                else
                if (isset($territoryDataList[$territory]))
                {
                    $languageNameList[$localeCode] = $territoryDataList[$territory];
                }
                else
                if (isset($languageDataList[$locale]))
                {
                    $languageNameList[$localeCode] = $languageDataList[$locale];
                }
                else
                {
                    continue;
                }
            }
        }
        $languageNameList = array_merge(array($defaultLanguage => $defaultLanguage), $languageNameList);
        return $languageNameList;
    }

}
